package main

type pair struct {
	x, y int
}

var dirs = []pair{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}

func islandPerimeter(grid [][]int) int {
	n, m := len(grid), len(grid[0])
	var res int

	for i, row := range grid {
		for j, v := range row {
			if v == 1 {
				for _, d := range dirs {
					if x, y := i+d.x, j+d.y; x < 0 || x >= n || y < 0 || y >= m || grid[x][y] == 0 {
						res++
					}
				}
			}
		}
	}

	return res
}
